package com.awifi.demo.netty.chat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;

/**
 * @description: ToDo
 * @author: marin
 * @time: 2020/9/14 9:36
 */
public class NIOChatServer {
    private Selector selector;
    private ServerSocketChannel socketChannel;
    private static final int PORT=6667;

    //构造器初始化

    public NIOChatServer() {
        try {
            selector = Selector.open();
            socketChannel = ServerSocketChannel.open();
            socketChannel.socket().bind(new InetSocketAddress(PORT));
            socketChannel.configureBlocking(false);
            socketChannel.register(selector, SelectionKey.OP_ACCEPT);
        }catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void listen() throws IOException {
        try {
            //循环获取是否有连接
            while (true) {
                int select = selector.select(2000);
                if (select > 0) {
                    Iterator<SelectionKey> iterators = selector.selectedKeys().iterator();
                    while (iterators.hasNext()) {
                        SelectionKey key = iterators.next();
                        if (key.isAcceptable()) {
                            SocketChannel channel = socketChannel.accept();
                            channel.configureBlocking(false);
                            channel.register(selector,SelectionKey.OP_READ);
                            System.out.println("from "+ channel.getRemoteAddress() +"is Login");
                        }
                        if (key.isReadable()) {
                            readData(key);
                        }
                        iterators.remove();
                    }
                } else {
                    System.out.println("wait 。 。 。");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (socketChannel != null) {
                socketChannel.close();
            }
            if (selector != null) {
                selector.close();
            }
        }
    }

    private void readData(SelectionKey key) {
        SocketChannel channel = null;
        try {
            channel = (SocketChannel) key.channel();
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            int read = channel.read(byteBuffer);
            if (read > 0 ) {
                String msg = new String(byteBuffer.array());
                System.out.println("client message:"+ msg);
                //向其他客户端打开消息
                transformToOther(msg,channel);
            }
        } catch (Exception e) {
            try {
                System.out.println(channel.getRemoteAddress() +"离线了。。。");
                key.cancel();
                channel.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        }
    }

    public void transformToOther(String msg,SocketChannel channel) throws IOException {
        System.out.println("服务器转发消息中。。。");
        for (SelectionKey key : selector.keys()) {
            if (key.channel() != channel && key.channel() instanceof SocketChannel) {
                SocketChannel desc = (SocketChannel) key.channel();
                ByteBuffer wrap = ByteBuffer.wrap(msg.getBytes());
                desc.write(wrap);
            }
        }
    }
    public static void main(String[] args) throws IOException {
        NIOChatServer nioChatServer = new NIOChatServer();
        nioChatServer.listen();
    }
}
